<script setup>
import { ref, computed, getCurrentInstance, reactive } from 'vue'
import { useAllDataStore } from '@/stores'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'; // 统一导入 API

const store = useAllDataStore()
const getImageUrl = (user) => {
    return new URL(`../assets/images/${user}.png`, import.meta.url).href
}
const handleCollapse = () => {
    store.state.isCollapse = !store.state.isCollapse
}
const router = useRouter()
const handleLoginOut = () => {
    store.clean()
    router.push('/login')
}

// 修改密码逻辑
const { proxy } = getCurrentInstance()
const passwordDialogVisible = ref(false);
const formPassword = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
});

const showPasswordDialog = () => {
    passwordDialogVisible.value = true;
};

// 自定义验证器，用于确认密码字段
const validateConfirmPassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请确认新密码'));
    } else if (value !== formPassword.newPassword) {
        callback(new Error('两次输入密码不一致'));
    } else {
        callback();
    }
};

// 验证规则
const rules = {
    currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
        // 可以添加更多规则，如最小长度等
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' },
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' },
    ],
};

const onSubmit = async () => {
    const formRef = proxy.$refs['passwordForm'];
    try {
        await formRef.validate(); // 验证表单
        const res = await api.employee.updatePassword(formPassword); // 如果验证通过，则发送请求
        passwordDialogVisible.value = false; // 关闭对话框
        ElMessage({
            showClose: true,
            message: '修改成功',
            type: 'success'
        });
        proxy.$refs['passwordForm'].resetFields();  // 重置表单字段
    } catch (error) {
        // 处理验证错误，这里可以不做处理，因为 Element Plus 会自动显示验证错误消息
        console.error('表单验证失败', error);
    }
};

// 关闭对话框并重置表单
const handleClose = () => {
    passwordDialogVisible.value = false;
    proxy.$refs['passwordForm'].resetFields();  // 重置表单字段
};

</script>

<template>
    <div class="header">
        <div class="l-content">
            <el-button size="small" @click="handleCollapse" class="collapse-btn">
                <component class="icons" is="menu"></component>
            </el-button>

            <el-breadcrumb separator="/" class="bread">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="r-content">
            <el-dropdown>
                <span class="el-dropdown-link">
                    <img :src="getImageUrl('user-default')" class="user" />
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item @click="showPasswordDialog">修改密码</el-dropdown-item>
                        <el-dropdown-item @click="handleLoginOut">退出</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>

            <!-- 修改密码对话框 -->
            <el-dialog v-model="passwordDialogVisible" :title="'修改密码'" width="30%" :before-close="handleClose">
                <el-form :model="formPassword" :rules="rules" ref="passwordForm">
                    <el-form-item label="当前密码" prop="oldPassword">
                        <el-input type="password" v-model="formPassword.oldPassword" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword">
                        <el-input type="password" v-model="formPassword.newPassword" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="确认新密码" prop="confirmPassword">
                        <el-input type="password" v-model="formPassword.confirmPassword" show-password></el-input>
                    </el-form-item>
                </el-form>
                <el-row style="justify-content: flex-end">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                </el-row>
            </el-dialog>
        </div>
    </div>
</template>

<style lang="less" scoped>
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 60px;
    background-color: #ffffff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    padding: 0 20px;
}

.icons {
    width: 20px;
    height: 20px;
}

.l-content {
    display: flex;
    align-items: center;
    gap: 20px;

    .collapse-btn {
        border: none;
        background: transparent;
        padding: 8px;
        transition: all 0.3s ease;

        &:hover {
            background-color: #f0f2f5;
            border-radius: 8px;
        }
    }
}

.r-content {
    .user {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        cursor: pointer;
        transition: all 0.3s ease;
        &:hover {
            transform: scale(1.1);
        }
    }
}

:deep(.bread span) {
    color: #606266 !important;
    cursor: pointer !important;
}
</style>